import {
  Card,
  Table,
  Button,
  Tooltip,
  InputNumber,
  Input,
  Form,
  Popconfirm,
  message,
  DatePicker,
  Select,
  Radio
} from 'antd';
import React, { Component } from 'react';
import { connect } from 'dva';
import SearchForm from '../../components/AutoForm/SearchForm';
import moment from 'moment';
import EditForm from '../../components/AutoForm/EditForm';
import {DriverSelect} from '../../components/Selection/DriverSelect';
const ButtonGroup = Button.Group;
const EditableContext = React.createContext();
const { TextArea } = Input;
const { Option } = Select;

@connect(({ splitOrder }) => ({
  requiredCols: splitOrder.requiredCols,
}))
class EditableCell extends Component {
  getInput = dataIndex => {
    switch (dataIndex) {
      case 'busType':
        return (
          <Select style={{ width: 100 }}>
            <Option value="LD">零担</Option>
            <Option value="DC">单程</Option>
            <Option value="WF">往返</Option>
          </Select>
        );
      case 'loadingPlace':
        return <TextArea rows={3} />;
      case 'loadoffPlace':
        return <TextArea rows={3} />;
      case 'loadNo':
        return <Input readOnly={true} />;
      case 'pickDate':
        return <DatePicker />;
      case 'aogDate':
        return <DatePicker />;
      case 'amount':
        return <InputNumber />;
      case 'volume':
        return <InputNumber />;
      case 'weight':
        return <InputNumber />;
      case 'vprice':
        return <InputNumber />;
      case 'wprice':
        return <InputNumber />;
      case 'pickFee':
        return <InputNumber />;
      case 'arteryFee':
        return <InputNumber />;
      case 'dropoffFee':
        return <InputNumber />;
      case 'workoverFee':
        return <InputNumber />;
      case 'loadupFee':
        return <InputNumber />;
      case 'loadoffFee':
        return <InputNumber />;
      case 'carFee':
        return <InputNumber />;
      case 'fuelFee':
        return <InputNumber />;
      case 'callbackFee':
        return <InputNumber />;
      case 'escortinFee':
        return <InputNumber />;
      case 'tipFee':
        return <InputNumber />;
      case 'shuttleFee':
        return <InputNumber />;
      default:
        return <Input />;
    }
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      requiredCols,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: requiredCols[title],
              initialValue:
                dataIndex === 'pickDate' || dataIndex === 'aogDate'
                  ? record[dataIndex]
                    ? moment(record[dataIndex])
                    : moment()
                  : record[dataIndex],
            })(this.getInput(dataIndex))}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}
@connect(({ loading, splitOrder }) => ({
  tableLoading: loading.effects['splitOrder/page'],
  formLoading: loading.effects['splitOrder/costOrders'],
  rejectLoading: loading.effects['splitOrder/splitReject'],
  tableData: splitOrder.pageList,
  pagination: splitOrder.pagination,
  columns: splitOrder.columns,
  searchFields: splitOrder.searchFields,
  searchValues: splitOrder.searchValues,
  editId: splitOrder.editId,
  selectionIds: splitOrder.selectionIds,
  selectedRows: splitOrder.selectedRows,
  moneyModal: splitOrder.moneyModal,
  modalForm: splitOrder.modalForm,
  moneyRows: splitOrder.moneyRows,
  isDirty: splitOrder.isDirty,
  dirtyId: splitOrder.dirtyId,
}))
class NestTable extends Component {
  state = {
    sumCost: 0,
    sumText: '选中合计费用：0',
    sumCostText: '申请费用（合计：0）',
    rejectModal: false,
    rejectForm: {},
    rejectRows: [
      {
        cols: [
          {
            label: '驳回理由',
            name: 'rejectCase',
            md: 12,
            rules: [{ required: true, message: ' ' }],
            component: <TextArea rows={4} placeholder="请输入驳回理由" />,
          },
        ],
      },
    ],
  };

  componentDidMount() {
    this.handleSearch();
  }
  rowClassName = (record, index) => {
    if (record.status === 'SPLIT') {
      return 'orderParent';
    }
  };

  handleSearch = (flag) => {
    const { dispatch, pagination, searchValues } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      if(key === 'loadNo'){
        if(searchValues[key]['value']){
          const replace = searchValues[key]['value'].replace(" ", "\n");
          const loadNos = replace.split("\n");
          let loadNoParams = [];
          loadNos.forEach(load => {
            if(load){
              loadNoParams.push(load.trim());
            }
          })
          searchParam['loadNos'] = loadNoParams;
        }
      }
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
    };
    dispatch({
      type: 'splitOrder/page',
      payload: param,
    });
  };

  handleEdit(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'splitOrder/handleEdit',
      payload: key,
    });
  }

  handleSplit(record) {
    const { dispatch, dirtyId } = this.props;
    if (record.id !== dirtyId && dirtyId !== 0) {
      return message.error('请先提交拆好的订单！');
    }
    dispatch({
      type: 'splitOrder/handleSplit',
      payload: record,
    });
  }
  handleSearchChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'splitOrder/handleSearchChange',
      payload: fields,
    });
  };
  handleRollback = record => {
    const { dispatch } = this.props;
    let statusOk = true;
    if (record.status !== 'SPLITED') {
      statusOk = false;
    }
    if (record.children) {
      record.children.forEach(r => {
        if (r.status !== 'SPLITED') {
          statusOk = false;
        }
      });
    }
    if (!statusOk) {
      return message.error('订单状态异常！');
    }
    dispatch({
      type: 'splitOrder/rollback',
      payload: record,
    }).then(() => {
      this.handleSearch();
    });
  };

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'splitOrder/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  onSend = () => {
    const { dispatch, selectionIds, tableData, isDirty } = this.props;
    if (isDirty) {
      return message.error('请选提交订单后再申请费用！');
    }
    if (selectionIds.length !== 1) {
      return message.error('请选一条要提交的数据！');
    }
    const id = selectionIds[0];
    let pd = {};
    tableData.forEach(pl => {
      if (id === pl.id) {
        pd = pl;
      }
    });
    if (!Object.keys(pd).length) {
      return message.error('请选主单提交！');
    }
    dispatch({
      type: 'splitOrder/save',
      payload: pd,
    }).then(() => {
      this.handleSearch();
    });
  };

  handleModalChange = fields => {
    const { dispatch, modalForm } = this.props;
    const payload = { fields: fields };
    dispatch({
      type: 'splitOrder/handleModalChange',
      payload: payload,
    });

    /*if (parseFloat(fields[Object.keys(fields)[0]].value).toString() !== 'NaN') {}*/
      const newValue = {
        ...modalForm,
        ...fields,
      };
      let sumCost = 0;
      sumCost =
        newValue.pickFee.value +
        newValue.arteryFee.value +
        newValue.dropoffFee.value +
        newValue.workoverFee.value +
        newValue.loadoffFee.value +
        newValue.carFee.value +
        newValue.fuelFee.value +
        newValue.callbackFee.value +
        newValue.escortinFee.value +
        newValue.tipFee.value +
        newValue.shuttleFee.value +
        newValue.loadupFee.value;
      this.setState({
        sumCostText: `申请费用（合计：${sumCost}）`,
        sumCost: sumCost
      });

  };

  handleRejectChange = fields => {
    this.setState({
      rejectForm: fields,
    });
  };

  onDel = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'splitOrder/handleDel',
      payload: record,
    });
    /*const { dispatch, selectionIds } = this.props;
    if(selectionIds.length !== 1){
      return message.error("请选一条要提交的数据！")
    }
    const id = selectionIds[0];
    dispatch({
      type: 'splitOrder/del',
      payload: {id: id}
    }).then(() => {
      this.handleSearch();
    })*/
  };

  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'splitOrder/handleEdit',
      payload: '',
    });
  };

  onMoney = () => {
    const { dispatch, selectionIds, tableData, isDirty } = this.props;
    if (isDirty) {
      return message.error('请选提交订单后再申请费用！');
    }
    if (!selectionIds.length) {
      return message.error('请选需要申请的订单！');
    }
    let isSub = true;
    selectionIds.forEach(id => {
      tableData.forEach(td => {
        if (td.id === id && td.children) {
          isSub = false;
        }
      });
    });
    if (!isSub) {
      return message.error('已经拆单，请选择子订单！');
    }
    dispatch({
      type: 'splitOrder/handleMoneyModal',
    });
    this.setState({
      sumCostText: `申请费用（合计：0）`,
    });
  };
  handleModalVisible = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'splitOrder/handleMoneyModal',
    });
  };
  handleRejectVisible = () => {
    this.setState({
      rejectModal: false,
    });
  };

  handleCostSub = fields => {
    const { dispatch, selectedRows, isDirty } = this.props;
    const {sumCost} = this.state;
    if(sumCost <= 0){
      return message.error('费用总额不能为0');
    }
    if (isDirty) {
      return message.error('请保存后再提交！');
    }
    const params = {
      orders: selectedRows,
      tmsCost: fields,
    };
    dispatch({
      type: 'splitOrder/costOrders',
      payload: params,
    }).then(() => {
      this.handleSearch();
    });
  };

  handleRejectSub = fields => {
    const { dispatch, selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一条要驳回的订单！');
    }
    if (selectedRows[0].status !== 'SPLIT') {
      return message.error('订单状态异常！');
    }
    dispatch({
      type: 'splitOrder/splitReject',
      payload: {
        ...selectedRows[0],
        ...fields,
      },
    }).then(() => {
      this.handleSearch();
      this.setState({ rejectModal: false });
    });
  };

  onReject = () => {
    const { dispatch, selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一条记录！');
    }
    if (selectedRows[0].status !== 'SPLIT') {
      return message.error('订单状态异常！');
    }
    this.setState({ rejectModal: true });
    /*dispatch({
      type: 'splitOrder/splitReject',
      payload: selectedRows[0],
    }).then(() => {
      this.handleSearch();
    });*/
  };

  save(form, record) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const { dispatch } = this.props;
      dispatch({
        type: 'splitOrder/handleSaveSplit',
        payload: {
          record: record,
          row: row,
        },
      });
    });
  }

  compPriceV = (e) => {
    debugger
    const { modalForm } = this.props
    const v = parseFloat(e.target.value)
    const f = modalForm.arteryFee.value
    if(v){
      const vp = (f/v).toFixed(2);
      this.handleModalChange({
        realVoPriceP: {
          name: 'realVoPriceP',
          value: vp,
        }
      })
    }
  }

  compPriceW = (e) => {
    debugger
    const { modalForm } = this.props
    const w = parseFloat(e.target.value)
    const f = modalForm.arteryFee.value
    if(w){
      const wp = (f/w).toFixed(2);
      this.handleModalChange({
        realWePriceP: {
          name: 'realWePriceP',
          value: wp,
        }
      })
    }

  }

  compPriceF = e => {
    debugger
    const { modalForm } = this.props
    const f = parseFloat(e.target.value)
    const w = modalForm.realWePrice.value
    const v = modalForm.realVoPrice.value
    if(w){
      const wp = (f/w).toFixed(2);
      this.handleModalChange({
        realWePriceP: {
          name: 'realWePriceP',
          value: wp,
        }
      })
    }
    if(v){
      const vp = (f/v).toFixed(2);
      this.handleModalChange({
        realVoPriceP: {
          name: 'realVoPriceP',
          value: vp,
        }
      })
    }
  }

  render() {
    const { rejectModal, rejectForm, rejectRows } = this.state;
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      moneyModal,
      modalForm,
      formLoading,
      rejectLoading,
      dispatch,
    } = this.props;

    const moneyRows = [
      {
        cols: [
          {
            label: '费用平均方式',
            name: 'avgFlag',
            md: 16,
            rules: [{ required: true, message: '必选' }],
            component: (
              <Radio.Group>
                <Radio.Button value="V">体积</Radio.Button>
                <Radio.Button value="W">重量</Radio.Button>
                <Radio.Button value="Z">整车</Radio.Button>
              </Radio.Group>
            ),
          },
        ],
      },
      {
        cols: [
          {
            label: '实际要车类型',
            name: 'realCarType',
            md: 8,
            component: (
              <Input placeholder="请输入实际要车类型" />
            ),
          },
        ],
      },
      {
        cols: [
          {
            label: '提货费',
            name: 'pickFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入提货费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '干线费',
            name: 'arteryFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber onBlur={this.compPriceF} placeholder="请输入干线费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '送货费',
            name: 'dropoffFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入送货费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '加点费',
            name: 'workoverFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入加点费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '装货费',
            name: 'loadupFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入账号" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '卸货费',
            name: 'loadoffFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入卸货费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '包车费',
            name: 'carFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入包车费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '燃油补助费',
            name: 'fuelFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入燃油补助费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '加班费',
            name: 'callbackFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入加班费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '押车费',
            name: 'escortinFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入押车费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '小费',
            name: 'tipFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入小费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '短驳费',
            name: 'shuttleFee',
            md: 6,
            rules: [{ required: true, message: ' ' }],
            component: <InputNumber placeholder="请输入短驳费" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '司机姓名',
            name: 'driver',
            md: 8,
            rules: [{ required: true, message: ' ' }],
            component: <DriverSelect />,
          },
        ],
      },
      {
        cols: [
          {
            label: '车牌号',
            name: 'carNo',
            md: 8,
            rules: [{ required: true, message: ' ' }],
            component: <Input placeholder="请输入车牌号" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '司机电话',
            name: 'drPhone',
            md: 8,
            rules: [{ required: true, message: ' ' }],
            component: <Input placeholder="请输入司机电话" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '司机身份证',
            name: 'drIdcard',
            md: 8,
            rules: [{ required: true, message: ' ' }],
            component: <Input placeholder="请输入司机身份证" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '账户姓名',
            name: 'accountName',
            md: 8,
            rules: [{ required: true, message: ' ' }],
            component: <Input placeholder="请输入账户姓名" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '银行卡号',
            name: 'bankAccount',
            md: 8,
            rules: [{ required: true, message: ' ' }],
            component: <Input placeholder="请输入银行卡号" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '实际体积',
            name: 'realVoPrice',
            md: 6,
            component:  <InputNumber onBlur={this.compPriceV} placeholder="请输入实际体积" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '实际重量',
            name: 'realWePrice',
            md: 6,
            component:  <InputNumber onBlur={this.compPriceW} placeholder="请输入实际重量" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '体积单价',
            name: 'realVoPriceP',
            md: 6,
            component:  <InputNumber disabled={true}  placeholder="请输入实际重量" />,
          },
        ],
      },
      {
        cols: [
          {
            label: '重量单价',
            name: 'realWePriceP',
            md: 6,
            component:  <InputNumber disabled={true}  placeholder="请输入实际重量" />,
          },
        ],
      },
    ];

    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const optColumns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.id,
        }),
      };
    });

    optColumns.push({
      title: '操作',
      key: 'operation',
      width: '100px',
      fixed: 'right',
      render: (text, record) => {
        const editable = editId === record.id;
        return editable ? (
          <ButtonGroup>
            <EditableContext.Consumer>
              {form => (
                <Tooltip placement="bottom" title="保存">
                  <Button size="small" onClick={() => this.save(form, record)} icon="save" />
                </Tooltip>
              )}
            </EditableContext.Consumer>

            <Popconfirm
              title="确认取消?"
              cancelText="取消"
              okText="确定"
              onConfirm={() => this.cancel(record.id)}
            >
              <Tooltip placement="bottom" title="撤回">
                <Button size="small" icon="rollback" />
              </Tooltip>
            </Popconfirm>
          </ButtonGroup>
        ) : (
          <ButtonGroup>
            {editId !== '' || record.parentId || record.status !== 'SPLIT' ? (
              ''
            ) : (
              <Tooltip placement="bottom" title="拆单">
                <Button size="small" icon="fullscreen" onClick={() => this.handleSplit(record)} />
              </Tooltip>
            )}
            {editId !== '' || record.parentId || record.status !== 'SPLITED' ? (
              ''
            ) : (
              <Tooltip placement="bottom" title="取消拆单">
                <Button size="small" icon="rollback" onClick={() => this.handleRollback(record)} />
              </Tooltip>
            )}
            {editId !== '' || !record.parentId || record.status !== 'SPLIT' ? (
              ''
            ) : (
              <div>
                <Tooltip placement="bottom" title="编辑">
                  <Button size="small" icon="edit" onClick={() => this.handleEdit(record.id)} />
                </Tooltip>
                <Tooltip placement="bottom" title="删除">
                  <Button size="small" icon="minus" onClick={() => this.onDel(record)} />
                </Tooltip>
              </div>
            )}
          </ButtonGroup>
        );
      },
    });
    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'splitOrder/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'splitOrder/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
      getCheckboxProps: record => ({
        disabled: !(record.status === 'SPLIT' || record.status === 'SPLITED'),
      }),
    };

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="拆单->操作"
          moneyText="申请费用"
          layout="inline"
          onFieldsChange={this.handleSearchChange}
          onSubmit={() => {this.handleSearch('btn')}}
          onSend={this.onSend}
          onMoney={this.onMoney}
          onDel={this.onDel}
          isSend={true}
          isDel={false}
          isMoney={true}
          isReject={true}
          onReject={this.onReject}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <EditableContext.Provider value={this.props.form}>
          <Table
            defaultExpandAllRows={true}
            components={components}
            loading={tableLoading}
            columns={optColumns}
            rowSelection={rowSelection}
            dataSource={tableData}
            size="small"
            bordered
            rowKey="id"
            scroll={{ x: 'max-content' }}
            rowClassName={this.rowClassName}
            pagination={pagination}
          />
        </EditableContext.Provider>
        <EditForm
          title={this.state.sumCostText}
          rows={moneyRows}
          fieldValue={modalForm}
          onFieldsChange={this.handleModalChange}
          onCancel={this.handleModalVisible}
          onOk={this.handleCostSub}
          confirmLoading={formLoading}
          visible={moneyModal}
        />

        <EditForm
          title="驳回至输单"
          rows={rejectRows}
          fieldValue={rejectForm}
          onFieldsChange={this.handleRejectChange}
          onCancel={this.handleRejectVisible}
          onOk={this.handleRejectSub}
          confirmLoading={rejectLoading}
          visible={rejectModal}
        />
      </Card>
    );
  }
}

const EditableFormTable = Form.create()(NestTable);
export default EditableFormTable;
